<template>
  <div class="create">
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      :before-close="close"
      custom-class="createDrawer"
    >
      <div v-loading="loading">
        <el-tabs tab-position="left">
          <el-tab-pane
            ><span slot="label"><i class="el-icon-document"></i> 项目信息</span>
            <div>
              <el-form
                :model="form"
                :rules="rules"
                ref="ruleForm"
                class="demo-ruleForm"
              >
                <el-form-item prop="title" label-width="0">
                  <el-input
                    type="textarea"
                    autosize
                    placeholder="请输入项目标题"
                    v-model="form.title"
                    class="proTitle"
                    :readonly="isDetail"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item label="项目编码" prop="code" label-width="120px">
                  <el-input
                    type="number"
                    v-model="form.code"
                    placeholder="请输入项目编码"
                     :readonly="isDetail"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="项目头像"
                  prop="avater"
                  label-width="120px"
                  class="avater_pro"
                >
                  <span @click="handleViewAvatar"
                    ><el-avatar
                      shape="circle"
                      :size="60"
                      fit="fill"
                      style="cursor: pointer"
                      :src="
                        form.avater.url ||
                        require('../../../../../assets/images/avater.png')
                      "
                    ></el-avatar
                  ></span>
                  <el-upload
                    style="margin-left: 12px"
                    class="upload-demo"
                    :action="uploadImgUrl"
                    :headers="headers"
                    :file-list="[form.avater]"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-success="uploadSuccess"
                    accept=".png,.jpg,.gif,.jpeg"
                    v-if="!isDetail"
                  >
                    <el-button size="small" round>修改头像</el-button>
                  </el-upload>
                </el-form-item>
                <el-form-item label="项目时间" prop="time" label-width="120px">
                  <el-date-picker
                    v-model="form.time"
                    type="daterange"
                    range-separator=" - "
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                     :readonly="isDetail"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item
                  label="项目描述"
                  prop="description"
                  label-width="120px"
                >
                  <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入项目描述"
                    v-model="form.description"
                    show-word-limit
                    :maxlength="1000"
                    :readonly="isDetail"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="公开项目"
                  prop="openFlag"
                  label-width="120px"
                >
                  <el-switch
                    v-model="form.openFlag"
                    active-text="是"
                    inactive-text="否"
                    active-value="1"
                    inactive-value="0"
                    :disabled="isDetail"
                  >
                  </el-switch>
                </el-form-item>
                <el-form-item
                  label="主题色"
                  prop="themeColor"
                  label-width="120px"
                >
                  <el-color-picker
                    v-model="form.themeColor"
                    :disabled="isDetail"
                    show-alpha
                    :predefine="[
                      '#ff4500',
                      '#ff8c00',
                      '#ffd700',
                      '#90ee90',
                      '#00ced1',
                      '#1e90ff',
                      '#c71585',
                      'rgba(255, 69, 0, 0.68)',
                      'rgb(255, 120, 0)',
                      'hsv(51, 100, 98)',
                      'hsva(120, 40, 94, 0.5)',
                      'hsl(181, 100%, 37%)',
                      'hsla(209, 100%, 56%, 0.73)',
                      '#c7158577',
                    ]"
                  >
                  </el-color-picker>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane
            ><span slot="label"><i class="el-icon-user"></i> 项目角色</span>
            <div>
              <el-card
                class="box-card"
                shadow="never"
                v-for="(item, index) in roleList"
                :key="index"
                style="margin-bottom: 12px"
              >
                <div slot="header" class="clearfix">
                  <div style="display: flex; align-items: center">
                    <span
                      style="font-size: 14px; color: #666"
                      v-if="!item.edit"
                      @click="handleViewInput(item, index)"
                      >{{ item.name }}</span
                    >
                    <el-input
                      v-model="item.name"
                      placeholder="请填写角色名称（必填）"
                      clearable=""
                      :ref="`autofocus${index}`"
                      @blur="item.edit = !item.edit"
                      v-else
                    ></el-input>
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      size="mini"
                      style="margin-left: 12px"
                      v-if="index !== 0 && !isDetail"
                      @click="handleViewInput(item, index)"
                    ></el-button>
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      size="mini"
                      v-if="index !== 0 && !isDetail"
                      @click="handleDeleteRole(index)"
                    ></el-button>
                  </div>
                </div>
                <div class="pro_role_personnel">
                  <span class="title">人员</span>
                  <div style="display: flex; flex-wrap: wrap">
                    <div
                      class="personnelItem"
                      v-for="val in item.userIds"
                      :key="val.userId"
                    >
                      <img :src="val.avater" alt="" v-if="val.avater" />
                      <span v-else>{{ val.nickName[0] }}</span>
                      <div>{{ val.nickName }}</div>
                    </div>
                    <i
                      class="el-icon-circle-plus-outline"
                      @click="handleUserClick(index)"
                     v-if="!isDetail"
                      style="
                        margin-top: 6px;
                        font-size: 25px;
                        color: #999;
                        cursor: pointer;
                      "
                    ></i>
                  </div>
                </div>
                <div class="pro_role_role">
                  <span class="title" style="margin-top: 0">权限</span>
                  <div style="display: flex; flex-wrap: wrap">
                    <el-checkbox
                      v-model="val.isChoose"
                      :disabled="index === 0 || isDetail"
                      :label="val.code"
                      v-for="val in item.permissions"
                      :key="val.code"
                      >{{ val.opt }}</el-checkbox
                    >
                  </div>
                </div>
              </el-card>
              <el-button
                type="primary"
                size="mini"
                style="margin: 12px 0 0 0"
                @click="handleAddRule"
                v-if="!isDetail"
                >添加角色</el-button
              >
            </div>
          </el-tab-pane>
          <el-tab-pane :disabled="true"
            ><span slot="label"
              ><i class="el-icon-folder-checked"></i> 任务属性</span
            ></el-tab-pane
          >
        </el-tabs>
        <div class="footerDrawer" :style="{justifyContent:isDetail ? 'flex-end' : 'center'}">
          <div>
            <el-button @click="close" >取消</el-button>
            <el-button
              type="primary"
              style="margin-left: 100px"
              @click="save"
              :loading="loading"
              v-if="!isDetail"
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </el-drawer>
    <el-image
      ref="previewImg"
      :src="form.avater.url"
      :preview-src-list="[form.avater.url]"
      style="width: 100%; height: 100%"
    >
    </el-image>
    <userModal
      ref="userModal"
      v-if="userModalOpen"
      :multiple="true"
      :handleUserSubmit="handleUserSubmit"
      :close="closeUserModal"
      :open="userModalOpen"
    />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import userModal from "@/views/taskMassage/components/task/components/userModal.vue";
import { permissionList, createProject, detail } from "@/api/task/project.js";
import moment from "moment";
export default {
  components: {
    userModal,
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    close: {
      type: Function,
      default: () => {},
    },
    title: {
      type: String,
      default: "项目",
    },
    getList: {
      type: Function,
      default: () => {},
    },
    detailId: {
      type: String,
      default: "",
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      userModalOpen: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      loading: false,
      currentIndex: undefined,
      form: {
        avater: {
          openFlag: "0",
          themeColor: "rgba(244, 6, 6, 1)",
        },
      },
      rules: {
        title: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        time: [
          { required: true, message: "请选择项目时间", trigger: "change" },
        ],
        code: [
          { required: true, message: "请输入项目编码", trigger: "blur" },
          {
            pattern: /^[0-9]*$/,
            message: "项目编码之能输入数字",
            trigger: "blur",
          },
          {
            min: 3,
            max: 6,
            message: "项目编码长度必须介于 3 和 6 之间",
            trigger: "blur",
          },
        ],
      },
      roleList: [],
      perList: [],
    };
  },
  async mounted() {
    await this.getPermissionList();
    if (this.detailId) {
      await this.getDetail();
    } else {
      this.roleList = [
        {
          name: "项目管理员",
          permissions: await this.addIsChosoe(true),
          userIds: [this.$store.state.user.loginInfo],
        },
      ];
    }
  },
  methods: {
    async getDetail() {
      this.loading = true;
      const res = await detail(this.detailId);
      if (res.code === 200) {
        const data = res.data;
        this.form = {
          id: data.id,
          avater: { url: data.avatar },
          description: data.description,
          time: [data.startTime, data.endTime],
          openFlag: data.openFlag,
          themeColor: data.themeColor,
          code: data.code,
          title: data.title,
        };
        const list = [];
        const permissData = await this.addIsChosoe(false);
        data.roleList?.forEach((item,index) => {
          const itemData = { id: item.id, name: item.name };
          if(index !== 0) {
            itemData.edit = false
          }
          // 权限列表
          if (item.permissions && item.permissions?.split(",")?.length) {
            const permissionsArr = item.permissions?.split(",");
            const perList = JSON.parse(JSON.stringify(permissData));
            perList.forEach((val) => {
              if (permissionsArr.includes(val.code)) {
                val.isChoose = true;
              }
            });
            itemData.permissions = perList;
          }
          // 用户列表
          if (item.users.length) {
            const userList = []
            item.users.forEach((val) => {
              val.nickName = val.name;
              val.userId = val.id;
              val.avater = val.avatar;
              userList.push(val)
            });
            itemData.userIds = userList;
          }
          list.push(itemData);
        });
        
        this.roleList = list
      }
      this.loading = false;
    },
    async getPermissionList() {
      const res = await permissionList();
      this.perList = res.data;
    },
    async addIsChosoe(bol) {
      const list = JSON.parse(JSON.stringify(this.perList));
      list.forEach((item) => {
        item.isChoose = bol;
      });
      return list;
    },
    save() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const {
            code,
            title,
            avater,
            description,
            openFlag,
            time,
            themeColor,
            id
          } = this.form;
          const params = {
            id,
            code,
            title,
            description,
            openFlag,
            themeColor,
            avatar: avater?.url,
            startTime: moment(time?.[0]).format("YYYY-MM-DD"),
            endTime: moment(time?.[1]).format("YYYY-MM-DD"),
          };
          const roleList = [];
          for (let i = 0; i < this.roleList.length; i++) {
            const item = this.roleList[i];
            const obj = {
              name: item.name,
            };

            if (item.userIds?.length) {
              const userIds = [];
              for (let x = 0; x < item.userIds.length; x++) {
                if (item.userIds[x].userId) {
                  userIds.push(item.userIds[x].userId);
                }
              }
              obj.userIds = userIds.toString();
            }
            if (item.permissions?.length) {
              const permissions = [];
              for (let x = 0; x < item.permissions.length; x++) {
                if (item.permissions[x].code && item.permissions[x].isChoose) {
                  permissions.push(item.permissions[x].code);
                }
              }
              obj.permissions = permissions.toString();
            }
            roleList.push(obj);
          }
          params.roleList = roleList;
          const res = await createProject(params);
          if (res.code === 200) {
            this.loading = false;
            this.$message.success(`${this.form.id ? "编辑" : "创建"}成功`);
            this.close("1");
            this.getList();
          }
        }
      });
    },
    handleViewInput(row, index) {
      if(this.isDetail) return
      if (index !== 0) {
        row.edit = !row.edit;
        this.$nextTick(() => {
          this.$refs[`autofocus${index}`][0].focus();
        });
      }
    },
    handleDeleteRole(index) {
      this.roleList.splice(index, 1);
    },
    async handleAddRule() {
      this.roleList.push({
        name: "请填写角色名称（必填）",
        userIds: [],
        permissions: await this.addIsChosoe(false),
        edit: false,
      });
    },
    handleUserClick(index) {
      this.userModalOpen = true;
      this.currentIndex = index;
      setTimeout(()=>{
          this.$refs.userModal.getViewData(this.roleList[index].userIds);
        },200)
    },
    handleUserSubmit(arr) {
      this.roleList[this.currentIndex].userIds = arr;
      this.userModalOpen = false;
    },
    closeUserModal() {
      this.userModalOpen = false;
    },
    handleViewAvatar() {
      if (this.form.avater.url) {
        this.$refs.previewImg.showViewer = true;
      }
    },
    // 文件上传前置
    beforeUpload(file) {
      const isLt = file.size / 1024 / 1024 < 5;
      if (!isLt) {
        this.$modal.msgError(`上传文件大小不能超过5MB!`);
        return false;
      }
      this.$modal.loading("正在上传，请稍候...");
    },
    uploadSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      if (response.code === 200) {
        this.form.avater = response.data;
      } else {
        this.$$message.error(res.msg);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.create {
  ::v-deep input::-webkit-outer-spin-button,
  ::v-deep input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }
  ::v-deep .el-card__header {
    background: #f7f7f7;
  }
  .pro_role_role {
    margin: 0 16px;
    padding: 20px;
    display: flex;
    align-items: flex-start;
    ::v-deep .el-checkbox {
      width: 20%;
      margin-bottom: 6px;
    }
  }
  .title {
    font-size: 14px;
    color: #666;
    margin-right: 12px;
    display: inline-block;
    width: 60px;
    margin-top: 6px;
  }
  .pro_role_personnel {
    margin: 0 16px;
    border-bottom: 1px solid #e6ebf5;
    padding: 20px;
    display: flex;
    align-items: flex-start;

    .personnelItem {
      display: flex;
      align-items: center;

      margin-right: 12px;
      margin-bottom: 12px;
      span {
        display: inline-block;
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background: #1890ff;
        color: #fff;
        line-height: 35px;
        text-align: center;
        font-size: 16px;
        position: relative;
        z-index: 2;
        cursor: pointer;
      }
      img {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        position: relative;
        z-index: 2;
        cursor: pointer;
      }
      div {
        font-size: 12px;
        position: relative;
        z-index: 1;
        color: #666;
        background: #e6e8eb;
        border-radius: 20px;
        padding: 4px 10px;
        margin-left: -10px;
        cursor: pointer;
      }
    }
  }
  .proTitle ::v-deep .el-textarea__inner {
    resize: none;
    line-height: 32px;
    font-size: 28px;
    min-height: 80px !important;
  }
  ::v-deep .el-form-item__label {
    text-align: left;
    padding-left: 20px;
  }
  .avater_pro {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    ::v-deep .el-form-item__content {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-left: 0 !important;
    }
  }
  ::v-deep .createDrawer {
    width: 50% !important;
    .el-drawer__body {
      padding: 12px 12px 12px 0;
    }
    .el-tabs__header {
      width: 15%;
    }
    .el-tabs__item {
      font-size: 14px;
      padding: 0;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding-left: 24px;
      height: 50px;
      line-height: 50px;
    }
    .is-active {
      background: #ecf5ff;
    }
    .el-tabs {
      height: 84vh;
      .el-tabs__content {
        height: 84vh;
        overflow-y: scroll;
        padding-bottom: 12px;
        padding-right: 12px;
      }
    }
    .el-tabs__active-bar {
      height: 50px !important;
      width: 3px;
    }
  }
  .footerDrawer {
    border-top: 2px solid #e6ebf5;
    display: flex;
    justify-content: center;
    padding: 12px;
    padding-bottom: 0;
  }
}
</style>